﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;

namespace Mefisto4.Core.MEF
{
    public static class CompositionContainerExtension
    {
        public static object GetExportedValue(this ExportProvider container, Type type)
        {
            // Gets a reference to the GetExportedValue<T> method
            var methodInfo = container.GetType()
                                      .GetMethods()
                                      .First(d => d.Name == "GetExportedValue"
                                               && d.GetParameters().Length == 0);

            // Creates an array of the generic types that the GetExportedValue<T> method expects
            var genericTypeArray = new [] { type };

            // Adds the generic types to the method
            methodInfo = methodInfo.MakeGenericMethod(genericTypeArray);

            // Invokes GetExportedValue<type>()
            return methodInfo.Invoke(container, null);
        }

        public static IEnumerable<object> GetExportedValues(this ExportProvider container, Type type)
        {
            // Gets a reference to the GetExportedValue<T> method
            var methodInfo = container.GetType()
                                      .GetMethods()
                                      .First(d => d.Name == "GetExportedValues"
                                               && d.GetParameters().Length == 0);

            // Creates an array of the generic types that the GetExportedValues<T> method expects
            var genericTypeArray = new [] { type };

            // Adds the generic types to the method
            methodInfo = methodInfo.MakeGenericMethod(genericTypeArray);

            // Invokes GetExportedValues<type>()
            return methodInfo.Invoke(container, null) as IEnumerable<object>;
        }
    }
}